package com.kaiyidiannao.activity.user_detail;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.kaiyidiannao.adapter.OrderCheckAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.common.pulltorefresh_view.DragListView;
import com.kaiyidiannao.common.util.DisplayUtil;
import com.kaiyidiannao.common.util.MySystemParams;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.Order;
import com.kaiyidiannao.model.bean.UserBean;
import com.kaiyidiannao.model.req.model.GetMyOrderDelete;
import com.kaiyidiannao.model.req.model.GetMyTrade;
import com.kaiyidiannao.view.ActionBarView;
import com.kaiyidiannao.view.MyDialogWaitingAndDel;
import com.taplinker.core.util.LogUtil;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by mark on 2014/4/16.
 */
public class OrderCheck extends BaseActionBarActivity implements Observer, MyDialogWaitingAndDel.IDialogOnclickInterface {

    private OrderCheckAdapter orderCheckAdapter = null;
    private DragListView baseList;
    private TextView orderNum, orderTime, orderTotal, isSend;
    private ArrayList<Order> orders = DataCenter.orders;
    private int currentPage = DataCenter.LISTVIEW_DEFAULT_PAGE;
    private ArrayList<UserBean> userBeans = DataCenter.userLogin;
    private String check;
    private LinearLayout orderCheckBg;
    private MyDialogWaitingAndDel myDialog;
    private View currentItemView;
    private int longClickPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_info);
        // 添加观察者
        DataCenter.getInstance().addObserver(this);
        showProgressDialog("正在加载");
        orderCheckBg = (LinearLayout) findViewById(R.id.orderCheckBg);
        Intent intent = getIntent();
        check = intent.getStringExtra("orderCheck");
        if (check.equals("orderCheck")) {
            orderCheckBg.setBackgroundResource(R.color.font_white);
        }
        initID();
        new GetMyTrade(userBeans.get(0).getUserid(), "1", DataCenter.LISTVIEW_DEFAULT_PAGE).execute();
        init();
    }

    @Override
    protected void onRestart() {

        new GetMyTrade(userBeans.get(0).getUserid(), "1", DataCenter.LISTVIEW_DEFAULT_PAGE).execute();
        super.onRestart();

    }

    private void initID() {
        orderNum = (TextView) findViewById(R.id.orderNum);
        orderTime = (TextView) findViewById(R.id.orderTime);
        orderTotal = (TextView) findViewById(R.id.orderTotal);
        isSend = (TextView) findViewById(R.id.isSend);
        baseList = (DragListView) findViewById(R.id.baseList);
        myDialog = new MyDialogWaitingAndDel(this, R.style.MyDialogStyle);
    }

    public void init() {

        orderCheckAdapter = new OrderCheckAdapter(this, orders);
        baseList.setAdapter(orderCheckAdapter);

        findActionBar();
        // Log.d("orders",orders.get(0).getAddtime());

        baseList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(OrderCheck.this, OrderDetail.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", orders.get(position - 1));
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

        baseList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                int[] location = new int[2];
                view.getLocationOnScreen(location);
                view.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));
                currentItemView = view;
                longClickPosition = position;
                DisplayMetrics displayMetrics = new DisplayMetrics();
                Display display = OrderCheck.this.getWindowManager().getDefaultDisplay();
                display.getMetrics(displayMetrics);
                WindowManager.LayoutParams params = myDialog.getWindow().getAttributes();
                params.gravity = Gravity.BOTTOM;

                float scale = MySystemParams.getInstance(OrderCheck.this).scale;
                params.y = display.getHeight() - location[1] - DisplayUtil.px2dip(20, scale);
                myDialog.getWindow().setAttributes(params);
                myDialog.setCanceledOnTouchOutside(true);
                myDialog.show();
                return false;
            }
        });

        myDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                currentItemView.setBackgroundColor(getResources().getColor(android.R.color.white));
            }
        });

        baseList.setOnRefreshListener(new DragListView.OnRefreshLoadingMoreListener() {
            @Override
            public void onRefresh() {
                if (DataCenter.userLogin.size() != 0) {
                    currentPage = 1;
                    new GetMyTrade(userBeans.get(0).getUserid(), "1", currentPage).execute();
                } else {
                    showToast(getText(R.string.no_network).toString());
                }
            }

            @Override
            public void onLoadMore() {
                if (DataCenter.userLogin.size() != 0) {
                    new GetMyTrade(userBeans.get(0).getUserid(), "1", ++currentPage).execute();
                } else {
                    showToast(getText(R.string.no_network).toString());
                }
            }
        });
    }

    private void findActionBar() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.setTitle("订单查看");
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;
        if (!HttpUtils.isConnected()) {
            baseList.onRefreshComplete();
            baseList.onLoadMoreComplete(false);
        }

        closeProgressDialog();

        if (flag == DataCenter.flag.GET_MY_TRADE_SUCCESS
                || flag == DataCenter.flag.GET_MY_TRADE_FAILED) { //类表数据

            String code = DataCenter.code;
            if (flag == DataCenter.flag.GET_MY_TRADE_SUCCESS) {
                if (code.equals(DataCenter.successFlag)) {
                    closeProgressDialog();
                    baseList.onLoadMoreComplete(false);
                    baseList.onRefreshComplete();
                    // String ordernum = orderNum.getText().toString();
                    orderCheckAdapter.notifyDataSetChanged();

                } else {
                    closeProgressDialog();
                    Toast.makeText(OrderCheck.this, DataCenter.msg, Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            if (flag == DataCenter.flag.GET_MY_TRADE_FAILED) {
                closeProgressDialog();
                //showToast(getString(R.string.no_network));
            }
        }

        if(flag == DataCenter.flag.GET_ORDER_DELETE_SUCCESS || flag == DataCenter.flag.GET_ORDER_DELETE_FAILED){
            String code = DataCenter.code;
            if(flag == DataCenter.flag.GET_ORDER_DELETE_SUCCESS){
                if (code.equals("1")){
                    orders.remove(longClickPosition - 1);
                    orderCheckAdapter.notifyDataSetChanged();
                    showToast("删除成功");
                }else{
                    showToast("删除失败");
                }
            }
            if (flag == DataCenter.flag.GET_ORDER_DELETE_FAILED) {
                showToast(getString(R.string.no_network));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.d(DataCenter.LOG_INFO, OrderCheck.class.getSimpleName() + ".onDestroy");
        DataCenter.orders.clear();
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);
    }

    @Override
    public void leftOnclick() {//代办
        myDialog.dismiss();
        currentItemView.setBackgroundColor(getResources().getColor(android.R.color.white));
        orderCheckAdapter.notifyDataSetChanged();
    }

    @Override
    public void rightOnclick() {//删除
        myDialog.dismiss();
        currentItemView.setBackgroundColor(getResources().getColor(android.R.color.white));
        try {
            if(orders.get(longClickPosition-1).getStatus().equals("0")){
                new GetMyOrderDelete(userBeans.get(0).getUserid(), orders.get(longClickPosition-1).getOrderid()).execute();
            }else{
                showToast("订单无法删除");
            }

        }catch (IndexOutOfBoundsException e){
            e.printStackTrace();
        }

    }

}
